package com.rungeek.sqlite;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.net.*;
 

public class ServerLogic
{
	private static Connection conn;
	private static Statement stat;
    public static void main(String[] args) throws Exception
    {
        Class.forName("org.sqlite.JDBC"); 
        conn = DriverManager.getConnection("jdbc:sqlite:test.db");
        stat = conn.createStatement();
        boolean exit = false;
        while (true)
        {
            //accept tcp connection
        	ServerSocket mySocket = null;
        	mySocket = new ServerSocket(9000);
        	
        	//read from the client to see what operation they wish to perform
        	//...
        	
        	//switching logic based on the desired operation
        	String operation;
        	
        	//if (operation.equalsIgnoreCase("login"))
        	String clientusername = "";
        	//read packet from user, save as clientusername
        	String clientip = "";
        	//read IP from user, save as clientip
        	String[][] clientfriends = HandleLogin(clientusername, clientip);
        	
        	
            if (exit)
            {
                break;
            }
        }
        
        conn.close();
    }
    
    //This method accepts a username for the user who just logged in
    //and returns a 2xn array of that user's friend name-IP pairs
    //for friends with a non-null IP (meaning they are logged in currently)
    public static String[][] HandleLogin(String username, String userip) throws SQLException
    {
    	//set user's status to online
    	String myquery = "UPDATE `Users` SET IP='"+userip+"' WHERE Username='"+username;
    	stat.executeQuery(myquery);
    	System.out.println("User's IP set: "+userip);

    	//count the number of friends this user has
    	myquery = "SELECT COUNT FROM `Friends` WHERE User1 = '"+username+"'";
    	ResultSet rs = stat.executeQuery(myquery);
    	int x = rs.getInt(0);
    	System.out.println("Retrieved "+x+" friends for user "+username);

    	//create a 2xn array of this user's friends
    	String[][] onlinefriends = new String[x][2];

    	//acquire a ResultSet of the user's friends
    	myquery = "SELECT * FROM `Friends` WHERE User1 = '"+username+"'";
    	rs = stat.executeQuery(myquery);

    	//loop through ResultSet, storing friendname+IP pairs
    	for(int i = 0; i < x; i++)
    	{
    		onlinefriends[i][0] = rs.getString(0);
    		onlinefriends[i][1] = rs.getString(0);
    	}

    	return onlinefriends;
    }

    public static boolean HandleAddFriend(String username1, String username2) throws SQLException {
    	//Add the relationship (username1 -> username2) to the database
    	//return true if successful, else false
    }
    
    public static boolean HandleRemFriend(String username1, String username2) throws SQLException {
    	//remove the relationship (username1 -> username2) from database
    	//return true if successful, else false
    }
    
    public static boolean HandleCreateUser(String username) throws SQLException {
    	//create a new database entry for username
    	//return true if successful, else false
    }
    
    public static boolean HandleExists(String username) throws SQLException {
    	//check database to see if user exists
    	//return true if it does, else false
    }
    /*
    public void TalkToDatabase(String query)
    {
         * 2 cases    
         * client friend logs in
         *      client sends server a message "I'm Online"
         *      server sends client's online friends a message that client is online
         *      server sends client a list of all friends and ip addresses
         *          grouping on whether or not the friends are online
         *          then subordered in ascending alphabetical order
         * client logs off
         *      client sends server message
         *      server pushes to all friends that are online
         *      client's friends receive messages and reorder lists
         *          grouping on whether or not the friends are online
         *          then subordered in ascending alphabetical order
        */
       
        /* code example
        stat.executeUpdate("drop table if exists people;");
        stat.executeUpdate("create table people (name, occupation);");
        PreparedStatement prep = conn.prepareStatement(
            "insert into people values (?, ?);");
 
        prep.setString(1, "Gandhi");
        prep.setString(2, "politics");
        prep.addBatch();
        prep.setString(1, "Turing");
        prep.setString(2, "computers");
        prep.addBatch();
        prep.setString(1, "Wittgenstein");
        prep.setString(2, "smartypants");
        prep.addBatch();
 
        conn.setAutoCommit(false);
        prep.executeBatch();
        conn.setAutoCommit(true);
 
        ResultSet rs = stat.executeQuery("select * from people;");
        while (rs.next()) {
            System.out.println("name = " + rs.getString("name"));
            System.out.println("job = " + rs.getString("occupation"));
        }
        rs.close();
    }
    }*/
   
} 
